package cn.mesmile.flink.monitor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.mysql.cj.util.TimeUtil;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Date;

/**
 * @author zb
 * @date 2021/8/29 0:18
 * @Description
 *  ProcessWindowFunction 方法说明
 *    一次性迭代整个窗口里的所有元素，通过Context，可以获取到事件、窗口和状态信息
 *    可以和ReduceFunction, AggregateFunction 来做增量计算
 *    在Agg方法做第2个参数 ，windowFunction 会把每个 key 的窗口聚合后的结果带上 上下文信息进行输出
 *    之前ProcessWindowFunction是获取整个窗口的全部元素，在agg方法里面是获取聚合后的结果，一个元素
 *    aggregate( AggregateFunction<T, ACC, V> aggFunction,
 *    ProcessWindowFunction<V, R, K, W> windowFunction )
 */
public class FlinkApiMonitorApp {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        environment.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
        environment.setParallelism(1);

        //java,2022-11-11 09-10-10,15
        DataStream<AccessLogDO> ds =  environment.addSource(new AccessLogSource());
        // 过滤
        SingleOutputStreamOperator<AccessLogDO> filterDS = ds.filter(new FilterFunction<AccessLogDO>() {
            @Override
            public boolean filter(AccessLogDO value) throws Exception {
                return StrUtil.isNotBlank(value.getUrl());
            }
        });
        //指定watermark
        SingleOutputStreamOperator<AccessLogDO> watermarkDS = filterDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                //指定允许乱序延迟的最大时间 3
                .<AccessLogDO>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                //指定POJO事件时间列，毫秒
                .withTimestampAssigner(
                        (event, timestamp) -> event.getCreateTime().getTime()
                )
        );
        //最后的兜底数据
        OutputTag<AccessLogDO> lateData = new OutputTag<AccessLogDO>("lateDataLog"){};

        //多个字段分组
        KeyedStream<AccessLogDO, Tuple2<String, Integer>> keyedStream = watermarkDS.keyBy(
                new KeySelector<AccessLogDO, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> getKey(AccessLogDO value) throws Exception {
                return Tuple2.of(value.getUrl(),value.getHttpCode());
            }
        });
        //开窗
        SingleOutputStreamOperator<ResultCount> aggregateDS = keyedStream.window(
                SlidingEventTimeWindows.of(Time.seconds(60), Time.seconds(5)))
                .allowedLateness(Time.minutes(1))
                .sideOutputLateData(lateData)
                .aggregate(new AggregateFunction<AccessLogDO, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    @Override
                    public Long add(AccessLogDO value, Long accumulator) {
                        return accumulator+1;
                    }
                    @Override
                    public Long getResult(Long accumulator) {
                        return accumulator;
                    }
                    @Override
                    public Long merge(Long a, Long b) {
                        return a+b;
                    }
                }, new ProcessWindowFunction<Long, ResultCount, Tuple2<String, Integer>, TimeWindow>() {
                    @Override
                    public void process(Tuple2<String, Integer> value, Context context, Iterable<Long> elements, Collector<ResultCount> out) throws Exception {
                        ResultCount resultCount = new ResultCount();
                        resultCount.setUrl(value.f0);
                        resultCount.setCode(value.f1);
                        long total = elements.iterator().next();
                        resultCount.setCount(total);
                        resultCount.setStartTime(DateUtil.formatDateTime(new Date(context.window().getStart())));
                        resultCount.setEndTime(DateUtil.formatDateTime(new Date(context.window().getEnd())));
                        out.collect(resultCount);
                    }
                });
        aggregateDS.print("接口状态码");
        aggregateDS.getSideOutput(lateData).print("late data");

        environment.execute();
    }
}
